module corrosion #(
    parameter
        FRAME_LINE = 16'd640,
        FRAME_ROW  = 16'd480
)(
    input                   clk             ,
    input                   rst_n           ,
    input                   img_vsync       ,
    input                   img_href        ,
    input       [15:0]      img_data        ,
    input                   data_valid      ,
    output reg              img_vsync_o     ,
    output reg              img_href_o      ,
    output reg              data_valid_o    ,
    output      [15:0]      img_data_o      
);
reg         matrix_r1;
reg         matrix_r2;
reg         matrix_r3;

wire [15:0] matrix_11;
wire [15:0] matrix_12;
wire [15:0] matrix_13;
wire [15:0] matrix_21;
wire [15:0] matrix_22;
wire [15:0] matrix_23;
wire [15:0] matrix_31;
wire [15:0] matrix_32;
wire [15:0] matrix_33;

wire matrix_img_vsync_o ;
wire matrix_img_href_o  ;
wire matrix_data_valid_o;

matrix_3x3_corrosion #(
    .FRAME_LINE  (FRAME_LINE),
    .FRAME_ROW   (FRAME_ROW )
) u_matrix_3x3_corrosion(
    .clk            (clk                ),
    .rst_n          (rst_n              ),
    .img_vsync      (img_vsync          ),
    .img_href       (img_href           ),
    .img_data       (img_data           ),
    .data_valid     (data_valid         ),
    .img_vsync_o    (matrix_img_vsync_o ),
    .img_href_o     (matrix_img_href_o  ),
    .data_valid_o   (matrix_data_valid_o),
    .matrix_11      (matrix_11          ),
    .matrix_12      (matrix_12          ),
    .matrix_13      (matrix_13          ),
    .matrix_21      (matrix_21          ),
    .matrix_22      (matrix_22          ),
    .matrix_23      (matrix_23          ),
    .matrix_31      (matrix_31          ),
    .matrix_32      (matrix_32          ),
    .matrix_33      (matrix_33          )
);

// outputs--------------------------------------------------------------
// img_data_o
always @(posedge clk or negedge rst_n) begin
    if(~rst_n)begin
        matrix_r1 <= 1'd0;
        matrix_r2 <= 1'd0;
        matrix_r3 <= 1'd0;
    end
    else begin
        matrix_r1 <= (matrix_11 != 16'h0) && (matrix_12 != 16'h0) && (matrix_13 != 16'h0);
        matrix_r2 <= (matrix_21 != 16'h0) && (matrix_22 != 16'h0) && (matrix_23 != 16'h0);
        matrix_r3 <= (matrix_31 != 16'h0) && (matrix_32 != 16'h0) && (matrix_33 != 16'h0);
    end
end

assign img_data_o = (matrix_r1 && matrix_r2 && matrix_r3) ? 16'hffff : 16'h0; // 0 为黑色 ffff为白色

// delay 1 clk
always @(posedge clk or negedge rst_n) begin
    if(~rst_n)begin
        img_vsync_o    <= 1'd0;
        img_href_o     <= 1'd0;
        data_valid_o   <= 1'd0;
    end
    else begin
        img_vsync_o     <= matrix_img_vsync_o ;
        img_href_o      <= matrix_img_href_o  ;
        data_valid_o    <= matrix_data_valid_o;
    end
end
endmodule